<template>
    <el-container>
        <el-main>
            <el-form :inline="true" class="demo-form-inline">
                <el-form-item label="课程编号">
                    <el-input v-model="courseId" placeholder="请输入课程编号"></el-input>
                </el-form-item>
                <el-form-item label="课程名称">
                    <el-input v-model="courseName" placeholder="请输入课程名称"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onSearch">查询</el-button>
                    <el-button type="success" @click="onReset">重置</el-button>
                    <el-button style="margin-left: 80px;" type="primary" @click="onAdd">新增</el-button>
                    <el-button type="danger" @click="onDeleteAll">一键删除</el-button>
                    <el-button type="success" @click="onPassAll">一键通过</el-button>
                    <el-button type="warning" @click="confirmExport">导出</el-button>
                </el-form-item>          
            </el-form>

                <el-table
                    :data="tableData"
                    style="width: 100%; margin-top: 25px"
                    v-loading="loading"
                    :row-key="rowKey"
                    @selection-change="handleSelectionChange"
                    >
                <el-table-column type="selection" :reserve-selection="true" width="55"></el-table-column>
                <el-table-column prop="courseId" label="课程编号"></el-table-column>
                <el-table-column prop="courseName" label="课程名称">
                    <template #default="scope">
                        <el-link @click="showCourseDetails(scope.row)">{{ scope.row.courseName }}</el-link>
                    </template>
                </el-table-column>
                <el-table-column prop="courseCover" label="课程封面" >
                    <template #default="scope">
                            <div class="cover-frame">
                            <img
                                :src="scope.row.courseCover"
                                alt="Course Cover"
                                class="cover-image"
                                @click="handlePictureCardPreview(scope.row.courseCover)"
                            />
                            </div>         
                    </template>
                </el-table-column>
                <!-- <el-table-column prop="courseIntro" label="课程简介" width="80"></el-table-column> -->
                <el-table-column prop="courseVideo" label="课程视频" >
                    <template #default="scope">
                      <a :href="scope.row.courseVideo" target="_blank">点击播放视频</a> 
                    </template>
                </el-table-column>
                <el-table-column prop="courseAuthor" label="课程作者" ></el-table-column>
                <!-- 根据status值显示不同内容 -->
                <el-table-column prop="status" label="审核操作">
                <template #default="scope">
                    <div v-if="scope.row.status === '审核中'">
                        <el-button size="default" type="success" @click="onPass(scope.row)">通过</el-button>
                        <el-button size="default" type="danger" @click="onUnPass(scope.row)">不通过</el-button>
                    </div>
                    <div v-else>
                    {{ scope.row.status }}
                    </div>
                </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button size="default" type="primary" @click="onEdit(scope.row)">编辑</el-button>
                        <el-button size="default" type="danger" @click="onDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <div class="pagination-container" style="margin-top: 20px">
                <el-pagination
                    background
                    layout="total, prev, pager, next, jumper"
                    :total="total"
                    :current-page="currentPage"
                    :page-size="pageSize"
                    @current-change="handlePageChange"
                    @size-change="handleSizeChange">
                </el-pagination>
            </div>

           <!-- 课程详细信息弹窗 -->
            <el-dialog :key="dialogKey" v-model="detailDialogVisible" title="课程详细信息" style="font: x-large;">
            <div class="dialog-section">
                <div class="dialog-header">
                <div class="course-name">
                    <h3>课程名称</h3><p></p>
                    <p>{{ selectedCourse.courseName }}</p>
                </div>
                <div class="course-cover">
                    <div class="cover-frame">
                    <img
                        :src="selectedCourse.courseCover"
                        alt="Course Cover"
                        class="cover-image"
                        @click="handlePictureCardPreview(selectedCourse.courseCover)"
                    />
                    </div>
                </div>
                </div>
            </div>
            <div class="dialog-section">
                <h3>课程简介</h3>
                <p>{{ selectedCourse.courseIntro }}</p>
            </div>
            <div class="dialog-section">
                <h3>课程视频</h3>
                <video controls class="course-video" style="width:90%">
                <source :src="selectedCourse.courseVideo" type="video/mp4">
                Your browser does not support the video tag.
                </video>
            </div>
            </el-dialog>

            <!-- 图片预览弹窗 -->
            <el-dialog v-model="dialogPreviewVisible">
                <img class="preview-image" :src="selectedCourse.courseCover" 
                alt="Preview Image" style="width: 85%;"/>
            </el-dialog>

            <!-- 新增对话框 -->
            <el-dialog v-model="dialogVisible" title="新增课程" class="dialog">
                <el-form :model="newCourse" 
                        ref="addFormRef"
                        style="max-width: 600px"
                        :rules="rules"
                        label-width="120px"
                        class="demo-ruleForm custom-form"
                        status-icon>
                    <el-form-item label="课程编号" prop="courseId">
                        <el-input v-model="newCourse.courseId" placeholder="请输入课程编号"></el-input>
                    </el-form-item>
                    <el-form-item label="课程名称" prop="courseName">
                        <el-input v-model="newCourse.courseName" placeholder="请输入课程名称"></el-input>
                    </el-form-item>
                    <el-form-item label="课程封面" prop="courseCover">
                        <el-upload
                            action="http://localhost:1111/file/uploadPicture"
                            list-type="picture"
                            :limit="1"
                            :on-exceed="handleExceed"
                            :on-success="handleCoverSuccess"
                            :before-upload="beforeAvatarUpload"
                            :file-list="fileListCover">
                            <el-button type="primary" style="margin-left: -125px;">点击上传图片</el-button>
                            <template #tip>
                            <div class="el-upload__tip">
                                请上传大小不超过2MB格式为jpg/png的图片                   
                             </div>
                            </template>
                        </el-upload>               
                    </el-form-item>
                    <el-form-item label="课程简介" prop="courseIntro">
                        <el-input v-model="newCourse.courseIntro" placeholder="请输入课程简介" type="textarea" autosize></el-input>
                    </el-form-item>
                    <el-form-item label="课程视频" prop="courseVideo">
                        <el-upload
                            action="http://localhost:1111/file/uploadVideo"
                            :limit="1"
                            :on-exceed="handleExceed"
                            :on-success="handleVideoSuccess"
                            :before-upload="beforeVideoUpload"
                            :file-list="fileListVideo">
                            <el-button type="primary" style="margin-left: -105px;">点击上传视频</el-button>
                            <template #tip>
                                <div class="el-upload__tip">请上传大小不超过20MB格式为mp4的文件</div>
                            </template>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="课程作者" prop="courseAuthor">
                        <el-input v-model="newCourse.courseAuthor" placeholder="请输入课程作者"></el-input>
                    </el-form-item>

                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitNewCourse">确认</el-button>
                </div>
            </el-dialog>

            <!-- 编辑对话框 -->
            <el-dialog v-model="editDialogVisible" title="编辑课程" class="dialog">
                <el-form :model="editCourse" 
                        ref="editFormRef"
                        style="max-width: 600px"
                        :rules="rules"
                        label-width="120px"
                        class="demo-ruleForm custom-form"
                        status-icon>
                    <el-form-item label="课程编号" prop="courseId">
                        <el-input v-model="editCourse.courseId" :disabled="true"></el-input>
                    </el-form-item>
                    <el-form-item label="课程名称" prop="courseName">
                        <el-input v-model="editCourse.courseName"></el-input>
                    </el-form-item>
                    <el-form-item label="课程封面" prop="courseCover">
                        <el-upload
                            action="http://localhost:1111/file/uploadPicture"
                            list-type="picture"
                            :on-success="handleCoverEditSuccess"
                            :before-upload="beforeAvatarUpload"
                            :file-list="fileListCover">
                            <el-button type="primary" >点击上传图片</el-button>
                            <template #tip>
                            <div class="el-upload__tip">
                                请上传大小不超过2MB格式为jpg/png的图片                   
                             </div>
                            </template>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="课程简介" prop="courseIntro" >
                        <el-input v-model="editCourse.courseIntro" type="textarea" autosize></el-input>
                    </el-form-item>
                    <el-form-item label="课程视频" prop="courseVideo">
                        <el-upload
                            action="http://localhost:1111/file/uploadVideo"
                            :on-success="handleVideoEditSuccess"
                            :before-upload="beforeVideoUpload"
                            :file-list="fileListVideo">
                            <el-button type="primary">点击上传视频</el-button>
                            <template #tip>
                                <div class="el-upload__tip">请上传大小不超过20MB格式为mp4的文件</div>
                            </template>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="课程作者" prop="courseAuthor">
                        <el-input v-model="editCourse.courseAuthor"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="editDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitEditCourse">确认</el-button>
                </div>
            </el-dialog>
        </el-main>
    </el-container>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, nextTick } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox, FormInstance, FormRules, UploadFile, UploadProps } from 'element-plus';
import { CourseTpye } from './courseTypes';
import upload from 'element-plus/es/components/upload/index.mjs';

const courseId = ref('');
const courseName = ref('');
const loading = ref(false);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(6);
const dialogVisible = ref(false);
const editDialogVisible = ref(false);
const detailDialogVisible = ref(false); // 新增的弹窗可见状态
const selectedCourse = reactive({
    courseName: '',
    courseCover: '',
    courseIntro: '',
    courseVideo: '',
});
const newCourse = reactive({
    courseId: '',
    courseName: '',
    courseCover: '',
    courseIntro: '',
    courseVideo: '',
    courseAuthor: '',
    enterprise: localStorage.getItem('enterprise'),
    status: '审核中',
});
const editCourse = reactive({
    courseId: '',
    courseName: '',
    courseCover: '',
    courseIntro: '',
    courseVideo: '',
    courseAuthor: '',
    status: '',
});
//多选框
const tableData = ref<CourseTpye[]>([]);
const selectedMultiCourses = ref<CourseTpye[]>([]);
const selectedMultiCourseIds = ref<Set<string>>(new Set());

const fetchCourse = async () => {
    loading.value = true;
    try {
        const response = await axios.get('http://localhost:1111/course/searchStatus', {
            params: {
                courseId: courseId.value || '',
                name: courseName.value || '',
                page: currentPage.value,
                size: pageSize.value,
                enterprise: ''
            },
        });
        tableData.value = response.data.Course;
        total.value = response.data.total;

        // // 恢复选中状态
        // tableData.value.forEach(course => {
        //     course._checked = selectedMultiCourseIds.value.has(course.courseId);
        // });
    } catch (error) {
        console.error(error);
    } finally {
        loading.value = false;
    }
};
// handleSelectionChange 方法
const handleSelectionChange = (val: CourseTpye[]) => {
    selectedMultiCourses.value = val;
    selectedMultiCourseIds.value.clear();
    selectedMultiCourses.value.forEach(course => {
        selectedMultiCourseIds.value.add(course.courseId);
    });
};
const rowKey = (row: CourseTpye) => {
    return row.courseId;
};
//一键删除
const onDeleteAll = () => {
    if (selectedMultiCourses.value.length === 0) {
        ElMessage({
            type: 'warning',
            message: '请选择需要删除的课程!',
        });
        return;
    }
    ElMessageBox.confirm(`此操作将永久删除选中的课程, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(async () => {
        try {
            const deleteRequests = selectedMultiCourses.value.map((course: any) => {
                return axios.delete(`http://localhost:1111/course/del`, {
                    params: { courseId: course.courseId }
                });
            });
            await Promise.all(deleteRequests);
            fetchCourse();
            ElMessage({
                type: 'success',
                message: '删除成功!',
            });
        } catch (error) {
            console.error("删除失败", error);
        }
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '已取消删除',
        });
    });
};
//一键通过
const onPassAll = () => {
    if (selectedMultiCourses.value.length === 0) {
        ElMessage({
            type: 'warning',
            message: '请选择通过审核的课程!',
        });
        return;
    }
    ElMessageBox.confirm(`此操作将审核通过选中的课程, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(async () => {
        try {
            const pass = true;
            const courseIds = selectedMultiCourses.value.map((course) => course.courseId);
            await axios.put('http://localhost:1111/course/updateStatus', {courseIds,pass});
            // selectedMultiCourses.value = [];
            selectedMultiCourseIds.value.clear();
            fetchCourse();
            ElMessage({
                type: 'success',
                message: '已全部通过选中的课程!',
            });
        } catch (error) {
            console.error("通过失败", error);
        }
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '已取消通过',
        });
    });
};
//审核是否通过
const onPass = async (row: any) => {
    try {   
        const pass = true; 
        const courseIds = [row.courseId]; 
        await axios.put('http://localhost:1111/course/updateStatus', { courseIds, pass });
        selectedMultiCourses.value = selectedMultiCourses.value.filter(course => course.courseId !== row.courseId);
        selectedMultiCourseIds.value.delete(row.courseId);
        fetchCourse();
        console.log(editCourse.status);
    } catch (error) {
        console.error(error);
    }
};

const onUnPass = async (row : any) => {
    try {   
        const pass = false; 
        const courseIds = [row.courseId]; //单个Id包装成数组
        await axios.put('http://localhost:1111/course/updateStatus', { courseIds, pass });
        selectedMultiCourses.value = selectedMultiCourses.value.filter(course => course.courseId !== row.courseId);
        selectedMultiCourseIds.value.delete(row.courseId);
        fetchCourse();
        console.log(editCourse.status);
    } catch (error) {
        console.error(error);
    }
}
// Ref 定义
const addFormRef = ref<FormInstance | null>(null);
const editFormRef = ref<FormInstance | null>(null);

//校验规则
const rules = reactive<FormRules<CourseTpye>>({
    courseId: [
    { required: true, message: '请输入课程编号', trigger: 'blur' },
    { min: 3, message: '课程编号最少为3位', trigger: 'blur' },
  ],
  courseName: [
    {
      required: true,message: '请输入课程名称',trigger: 'blur',
    },
  ],
  courseCover: [
    { required: true,message: '请上传课程封面',trigger: 'blur',
    },
  ],
  courseIntro: [
    {required: true,message: '请输入课程简介',trigger: 'blur',
    },
  ],
  courseVideo: [
    {required: true,message: '请上传课程视频',trigger: 'blur',
    },
  ],
  courseAuthor: [
    {required: true,message: '请输入课程作者',trigger: 'blur',
    },
  ],
  
})

onMounted(() => {
    fetchCourse();
});
//搜索
const onSearch  =  () => {
    fetchCourse()
};
//重置
const onReset = () => {
    courseName.value = '';
    courseId.value = '';
    fetchCourse();
};

// 新增
const submitNewCourse = () => {
  if (!addFormRef.value) return;
  addFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      const exists = tableData.value.some(course => course.courseId === newCourse.courseId);
      if (exists) {
        ElMessage.error('课程编号已经存在，请重新输入！');
        return;
      }
      try {
        await axios.post('http://localhost:1111/course/add', newCourse);
        fetchCourse();
        dialogVisible.value = false;
        
      } catch (error) {
        console.error(error);
      }
    } else {
      console.log('error submit!', fields);
    }
  });
};
const onAdd = () => {
  Object.assign(newCourse, { courseId: '', courseName: '', courseCover: '', courseIntro: '', courseVideo: '', courseAuthor: '', status: '审核中' });
  fileListCover.value = [];
  fileListVideo.value = [];
  dialogVisible.value = true;
};

// 编辑
const submitEditCourse = () => {
    if (!editFormRef.value) return;
    editFormRef.value.validate(async (valid) => {
        if (valid) {
            try {       
                await axios.put('http://localhost:1111/course/update', editCourse);
                fetchCourse();
                editDialogVisible.value = false;
            } catch (error) {
                console.error(error);
            }
        } else {
            console.log('error submit!');
        }
    });
};
//编辑回显
const onEdit = (row: any) => {
    Object.assign(editCourse, row);
    console.log(editCourse.courseCover)

    fileListCover.value = [{
        name: editCourse.courseCover.split('/').pop()||'',
        url: editCourse.courseCover,
        status: 'ready',
        uid: 1
    }];
    fileListVideo.value = [{
        name: editCourse.courseVideo.split('/').pop()||'',
        url: editCourse.courseVideo,
        status: 'ready',
        uid: 1
    }];

    editCourse.courseId = row.courseId;
    editCourse.courseName = row.courseName;
    editCourse.courseIntro = row.courseIntro;
    editCourse.courseAuthor = row.courseAuthor;
    editCourse.status = '审核中';
    editDialogVisible.value = true;
};
//删除
const onDelete = (row: any) => {
    // 删除逻辑
    const confirmDelete = async () => {
        try {
            console.log("删除"+row.courseId);
            await axios.delete(`http://localhost:1111/course/del`, {
                params: { courseId: row.courseId }
            });
            fetchCourse();
        } catch (error) {
            console.error("删除失败", error);
        }
    };

    // 弹出确认对话框
    ElMessageBox.confirm(`此操作将永久删除课程: "${row.courseName}", 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        confirmDelete();
        ElMessage({
            type: 'success',
            message: '删除成功!',
        });
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '已取消删除',
        });
    });
};
//导出
const confirmExport = () => {
    ElMessageBox.confirm('是否确认导出所有课程管理数据项?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        exportCourses();
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '已取消导出',
        });
    });
};
const exportCourses = async () => {
    try {
        const response = await axios.get('http://localhost:1111/course/export', {
            responseType: 'blob', // 指定响应数据的类型为 blob
        });
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.style.display = 'none';
        link.href = url;
        link.setAttribute('download', 'courses.xlsx'); // 设置下载文件的文件名
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
    } catch (error) {
        console.error('导出失败:', error);
        ElMessage.error('导出失败，请稍后重试');
    }
};

// 分页
const handlePageChange = (val: number) => {
    currentPage.value = val;
    fetchCourse();
};
const handleSizeChange = (val: number) => {
    pageSize.value = val;
    fetchCourse();
};

//详情
const dialogKey = ref(0); // 用于强制重新渲染
const showCourseDetails = async (row: any) => {
     Object.assign(selectedCourse, row);
     detailDialogVisible.value = true;
     // 强制更新视图
     dialogKey.value++; // 更新 key 以强制重新渲染
     await nextTick();
};
//查看大图
const dialogPreviewVisible = ref(false);
const handlePictureCardPreview = (imageUrl: string) =>{
    selectedCourse.courseCover = imageUrl;
    dialogPreviewVisible.value = true;
}
// 加入图片或者视频
const fileListCover = ref<UploadFile[]>([]);
const fileListVideo = ref<UploadFile[]>([]);

//上传图片
const handleCoverSuccess = (response: any) => {
    newCourse.courseCover = 'http://localhost:1111' + response.url;
    console.log(newCourse.courseCover);
    // fileListCover.value = [{
    //     name: response.file.name,
    //     url: newCourse.courseCover,
    //     status: 'ready',
    //     uid: response.file.uid
    // }];
};
//检查图片格式
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('请上传 JPG 或 PNG 格式的图片!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}
//修改图片
const handleCoverEditSuccess = (response: any, file: any) => {
    editCourse.courseCover = 'http://localhost:1111' + response.url; // 假设后端返回相对URL
    fileListCover.value = [{
        name: file.name,
        url: editCourse.courseCover,
        status:'ready', // 这个属性是可选的，用于表示上传状态
        uid: file.uid // 确保有一个唯一标识符
    }];
};

//上传视频
const handleVideoSuccess = (response: any) => {
    newCourse.courseVideo = 'http://localhost:1111' + response.url;
    // fileListVideo.value = [{
    //     name: response.file.name,
    //     url: newCourse.courseVideo,
    //     status: 'ready',
    //     uid: response.file.uid
    // }];
};
//修改视频
const handleVideoEditSuccess = (response: any, file: any) => {
    editCourse.courseVideo = 'http://localhost:1111' + response.url; // 假设后端返回相对URL
    fileListVideo.value = [{
        name: file.name,
        url: editCourse.courseVideo,
        status:'ready', // 这个属性是可选的，用于表示上传状态
        uid: file.uid // 确保有一个唯一标识符
    }];
};
//检查视频格式
const beforeVideoUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'video/mp4') {
    ElMessage.error('请上传 MP4 格式的视频!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 20) {
    ElMessage.error('视频大小不能超过 20MB!')
    return false
  }
  return true
};
//只能写一个
const handleExceed: UploadProps['onExceed'] = (files) => {   
  if (files.length > 1) {
    files.slice(1).forEach((file) => upload.value.clearFiles(file));
  }
  ElMessage.warning('最多只能上传一个文件!');
};

</script>

<style scoped>
.pagination-container {
    display: flex;
    justify-content: center;
    align-items: center;
}
.custom-form .el-form-item{
    margin-top: 25px;
    margin-bottom: 30px
    
}
.el-upload__tip{
    line-height: 1;
    color: red;
}

.dialog-section {
  border-bottom: 1px solid #eaeaea;
  padding: 10px 0;
}
.dialog-header {
  display: flex;
  align-items: center;
  padding-bottom: 10px;
}
.course-name {
  flex: 1;
}
.course-cover {
  flex: 1;
  text-align: center;
}
.cover-frame {
  display: inline-block;
  border: 1px dashed #ccc;
  padding: 5px;
  width: 150px;
  height: 150px;
}
.cover-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  cursor: pointer;
}

</style>
